<template>
  <div>
    <el-form ref="spuForm" :model="spuInfo" :rules="rules">
      <el-form-item label="SPU名称" label-width="80px" prop="spuName">
        <el-input v-model="spuInfo.spuName" placeholder="请输入SPU名称" />
      </el-form-item>
      <el-form-item label="SPU品牌" label-width="80px" prop="tmId">
        <el-select v-model="spuInfo.tmId" placeholder="请选择品牌">
          <el-option v-for="trademark in trademarkList" :key="trademark.id" :label="trademark.tmName" :value="trademark.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="SPU描述" label-width="80px" prop="description">
        <el-input v-model="spuInfo.description" type="textarea" placeholder="请输入SPU描述" />
      </el-form-item>
      <el-form-item label="SPU图片" label-width="80px" prop="spuImageList">
        <el-upload :class="{'spu-image-upload' : spuImageList.length >= 3}" action="/dev-api/admin/product/fileUpload" list-type="picture-card" :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload" accept=".jpg,.jpeg,.png" :limit="3" :file-list="spuImageList">
          <i class="el-icon-plus" />
          <div slot="tip" class="el-upload__tip">只能上传JPG、PNG、JPEG 格式图片，且不超过3M</div>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <el-form-item label="销售属性" label-width="80px" prop="spuSaleAttrList">
        <el-select v-model="spuInfo.spuSaleAttr" :placeholder="`还剩下${formatBaseSaleAttrList.length}个销售属性`">
          <el-option v-for="baseSaleAttr in formatBaseSaleAttrList" :key="baseSaleAttr.id" :label="baseSaleAttr.name" :value="baseSaleAttr.name" />
        </el-select>
        <el-button :disabled="!spuInfo.spuSaleAttr" type="primary" icon="el-icon-plus" style="margin-left:10px" @click="addSpuSaleAttr">添加销售属性值</el-button>
        <el-table border :data="spuInfo.spuSaleAttrList">
          <el-table-column type="index" label="序号" width="80" align="center" />
          <el-table-column label="属性名" prop="saleAttrName" width="130" />
          <el-table-column label="属性值列表">
            <template v-slot="{row}">
              <el-tag v-for="(tag, index) in row.spuSaleAttrValueList" :key="tag.saleAttrValueName" closable :disable-transitions="false" @close="handleClose(row, index)">
                {{ tag.saleAttrValueName }}
              </el-tag>
              <el-input
                v-if="row.inputVisible"
                ref="saveTagInput"
                v-model.trim="inputValue"
                class="input-new-tag"
                size="small"
                @keyup.enter.native="handleInputConfirm(row)"
                @blur="handleInputConfirm(row)"
              />
              <el-button v-else class="button-new-tag" size="small" @click="showInput(row)">+ 添加属性值</el-button>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{$index}">
              <el-tooltip content="删除属性" placement="top">
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="delSpuSaleAttr($index)" />
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-form-item label-width="80px">
        <el-button type="primary" @click="submitSpuForm">确定</el-button>
        <el-button @click="$emit('update:visible', 1)">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {
  reqGetALlTrademarkList, // 获取所有品牌名称
  reqGetBaseSaleAttrList, // 获取基本销售属性
  reqSaveSpuInfo, // 添加spuInfo
  reqGetSpuImageList, // 获取图片列表
  reqGetSpuSaleAttrList, // 获取属性列表
  reqUpdateSpuInfo // 更新spu
} from '@/api/product/spu'
import { mapState } from 'vuex'
export default {
  name: 'SaveSpu',
  props: {
    currentSpuInfo: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    const spuImageListValidate = (rule, value, callback) => {
      // if (!value.length) {
      //   callback('请至少上传一张图片')
      //   return
      // }
      callback()
    }
    const spuSaleAttrListValidate = (rule, value, callback) => {
      if (!value.length) {
        callback('请至少选择一个销售属性')
        return
      }
      if (value.some((item) => item.spuSaleAttrValueList.length === 0)) {
        // console.log(1)
        callback('销售属性值不能为空')
        return
      }
      callback()
    }
    return {
      // inputVisible: false,
      inputValue: '', // 表单中用于双向数据绑定 或是说用于收集数据的
      dialogImageUrl: '', // 图片的链接
      dialogVisible: false, // 上传图片成功后的预览
      trademarkList: [], // 所有的品牌数据列表
      baseSaleAttrList: [], // 所有的基础销售属性列表
      spuImageList: [], // 照片墙
      spuInfo: {
        // 最终添加SPU需要添加的属性如下
        spuSaleAttr: '', // 收集选中的销售属性
        spuName: '', // spu名称
        tmId: '', // spu品牌
        description: '', // spu描述
        spuImageList: [], // spu图片
        spuSaleAttrList: [], // 基本销售属性
        // category3Id: '' // 三级Id
        ...this.currentSpuInfo
      },
      rules: {
        spuName: [{ required: true, message: '请输入SPU名称', trigger: 'blur' }],
        tmId: [{ required: true, message: '请选择所属品牌', trigger: 'change' }],
        description: [{ required: true, message: '请输入SPU描述', trigger: 'blur' }],
        spuImageList: [{ required: true, validator: spuImageListValidate, trigger: 'change' }],
        spuSaleAttrList: [{ required: true, validator: spuSaleAttrListValidate, trigger: 'blur' }]
      }
    }
  },
  computed: {
    // 2.格式化spu图片
    // formatSpuImageList() {
    //   return this.spuInfo.spuImageList.map(item => {
    //     return {
    //       name: item.imgName,
    //       url: item.imgUrl
    //     }
    //   })
    // },
    // 1、过滤基本销售属性
    formatBaseSaleAttrList() {
      return this.baseSaleAttrList.filter((baseSaleAttr) => {
        return !this.spuInfo.spuSaleAttrList.find((item) => item.saleAttrName === baseSaleAttr.name)
      })
    },
    ...mapState('category', ['category3Id'])
  },
  async mounted() {
    try {
      const { id } = this.spuInfo
      let promises = [reqGetALlTrademarkList(), reqGetBaseSaleAttrList()]
      if (id) {
        promises = promises.concat([reqGetSpuImageList(id), reqGetSpuSaleAttrList(id)])
      }
      const [resTrademarkList, resBaseSaleAttrList, resSpuImageList, resSpuSaleAttrList] = await Promise.all(promises)
      this.trademarkList = resTrademarkList.data
      this.baseSaleAttrList = resBaseSaleAttrList.data
      if (resSpuImageList && resSpuImageList.code === 200) {
        this.spuInfo.spuImageList = resSpuImageList.data
        this.spuImageList = resSpuImageList.data
        // 2.格式化spu图片
        this.spuImageList = this.spuImageList.map(item => {
          return {
            name: item.imgName,
            url: item.imgUrl
          }
        })
        this.spuInfo.spuSaleAttrList = resSpuSaleAttrList.data
      }
    } catch (e) {
      this.$message.error('获取品牌和销售属性数据失败...')
    }
  },
  methods: {
    // 3.添加spu属性
    submitSpuForm() {
      this.$refs.spuForm.validate(async(valid) => {
        if (valid) {
          this.spuInfo.category3Id = this.category3Id
          // this.spuInfo.spuImageList = this.spuImageList
          this.spuInfo.spuImageList = this.spuImageList.map((item) => {
            return {
              imgName: item.name,
              imgUrl: item.response ? item.response.data : item.url
            }
          })
          if (!this.spuImageList.length) {
            this.$message.error('请至少选择一张图片')
            return
          }
          const { id } = this.spuInfo
          let res
          if (id) {
            // 此时是更新操作
            res = await reqUpdateSpuInfo(this.spuInfo)
          } else {
            res = await reqSaveSpuInfo(this.spuInfo)
          }
          if (res.code === 200) {
            // 提示添加成功
            this.$message.success(`${id ? '更新' : '添加'}spu成功`)
            // 跳转到spu列表页
            this.$emit('update:visible', 1)
          } else {
            this.$message.error(res.message)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 2.删除一项spu属性
    delSpuSaleAttr(index) {
      this.spuInfo.spuSaleAttrList.splice(index, 1)
    },
    // 1.添加spu属性
    addSpuSaleAttr() {
      const spuSaleAttrList = this.spuInfo.spuSaleAttrList
      // if (spuSaleAttrList.length && spuSaleAttrList[spuSaleAttrList.length - 1].spuSaleAttrValueList.length === 0) {
      //   this.$message.error('请添加属性值')
      //   return
      // }
      const id = this.baseSaleAttrList.find(item => item.name === this.spuInfo.spuSaleAttr).id
      if (!spuSaleAttrList.every((item) => item.spuSaleAttrValueList.length !== 0)) {
        return this.$message.error('属性对应的具体属性值不能为空')
      }
      spuSaleAttrList.push({
        baseSaleAttrId: id,
        saleAttrName: this.spuInfo.spuSaleAttr,
        spuSaleAttrValueList: [],
        inputVisible: false
      })
      this.spuInfo.spuSaleAttr = ''
    },
    // 动态编辑标签相关方法
    // handleClose(tag, row) {
    handleClose(row, index) {
      // row.spuSaleAttrValueList.splice(row.spuSaleAttrValueList.indexOf(tag), 1)
      row.spuSaleAttrValueList.splice(index, 1)
    },
    // 点击出现标签输入框
    showInput(row) {
      // row.inputVisible = true
      this.$set(row, 'inputVisible', true)
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 确认标签输入框的值
    handleInputConfirm(row) {
      const inputValue = this.inputValue
      if (row.spuSaleAttrValueList.find((item) => item.saleAttrValueName === inputValue)) {
        this.$message.error('属性值已经存在，请重新输入')
        row.inputVisible = false // 将输入框切换成按钮
        this.inputValue = '' // 清空输入框中的值 以便下一次继续添加
        return
      }
      const id = this.baseSaleAttrList.find((item) => item.name === row.saleAttrName).id
      if (inputValue) {
        row.spuSaleAttrValueList.push({
          baseSaleAttrId: id, // 销售属性对应的Id
          saleAttrName: row.saleAttrName, // 所属的销售属性 比如颜色 规格
          saleAttrValueName: inputValue // 详细的属性值 比如颜色中的红色
        })
      }
      row.inputVisible = false // 将输入框切换成按钮
      this.inputValue = '' // 清空输入框中的值 以便下一次继续添加
    },
    // 删除图片
    handleRemove(file, fileList) {
      // file 是当前被删除了的图片资料
      // file 是剩余的图片资料
      // console.log(file, fileList)
      // this.spuInfo.spuImageList = fileList
      this.spuImageList = fileList
    },
    // 图片预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 品牌图片上传成功
    handleAvatarSuccess(res, file, fileList) {
      // console.log(res, file)
      // this.spuInfo.spuImageList = fileList
      this.spuImageList = fileList
      this.$refs.spuForm.clearValidate(['spuImageList'])
    },
    // 图片上传前
    beforeAvatarUpload(file) {
      const avatarArr = ['image/jpeg', 'image/jpg', 'image/png']
      // const isJPG = file.type === 'image/jpeg'
      const isJPG = avatarArr.includes(file.type)
      const isLt3M = file.size / 1024 / 1024 < 3

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG、PNG、JPEG  格式!')
      }
      if (!isLt3M) {
        this.$message.error('上传头像图片大小不能超过 3MB!')
      }
      return isJPG && isLt3M
    }
  }
}
</script>

<style scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
